package com.cheng.xbsc.service.impl;

import com.cheng.xbsc.entity.Car;
import com.cheng.xbsc.entity.SysOrder;
import com.cheng.xbsc.mapper.CarMapper;
import com.cheng.xbsc.mapper.SysOrderMapper;
import com.cheng.xbsc.service.CarService;
import com.cheng.xbsc.util.LoginUserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class CarServiceImpl implements CarService {

    @Autowired
    private CarMapper carMapper;

    @Autowired
    private SysOrderMapper sysOrderMapper;


    /**
     * 查询购物车数量
     *
     * @return
     */
    @Override
    public Integer countByStatus() {
        return carMapper.countByStatus(LoginUserUtil.getUserId());
    }

    @Override
    public List<Car> findByStatus(String status) {
        return carMapper.findByStatus(status, LoginUserUtil.getUserId());
    }

    @Override
    public void updateNum(Integer carId, Integer goodNum) {
        carMapper.updateById(carId, goodNum);
    }

    @Override
    public void deleteById(Integer carId) {
        carMapper.deleteByPrimaryKey(carId);
    }

    @Override
    public void updateStatus(Integer carId) {
        carMapper.updateStatus(carId, "1");
    }

    @Override
    public void updateAllStatus(String status) {
        carMapper.updateAllStatus(LoginUserUtil.getUserId(), status);
    }

    @Transactional
    @Override
    public void doPay(Integer carId) {
        Car car = carMapper.selectByPrimaryKey(carId);
        //支付完创建一个订单
        SysOrder sysOrder = new SysOrder();
        sysOrder.setGoodsPic(car.getGoodsPic());
        sysOrder.setGoodsTitle(car.getGoodsTitle());
        sysOrder.setGoodPrice(car.getGoodsPrice());
        sysOrder.setCreateTime(new Date());
        sysOrder.setGoodNum(car.getGoodNum());
        sysOrder.setOrderStatus("0");
        sysOrder.setUserId(car.getUserId());
        sysOrder.setGoodId(car.getGoodsId());
        sysOrderMapper.insert(sysOrder);
        carMapper.updateStatus(carId, "2");
    }

    @Transactional
    @Override
    public void doPayAll() {
        List<Car> carList = carMapper.findByStatus("1", LoginUserUtil.getUserId());
        for (Car car : carList) {
            SysOrder sysOrder = new SysOrder();
            sysOrder.setGoodsPic(car.getGoodsPic());
            sysOrder.setGoodsTitle(car.getGoodsTitle());
            sysOrder.setGoodPrice(car.getGoodsPrice());
            sysOrder.setCreateTime(new Date());
            sysOrder.setGoodNum(car.getGoodNum());
            sysOrder.setOrderStatus("0");
            sysOrder.setUserId(car.getUserId());
            sysOrder.setGoodId(car.getGoodsId());
            sysOrderMapper.insert(sysOrder);
            carMapper.updateStatus(car.getId(), "2");
        }
    }
}
